package cn.bugstack.test;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;

import java.math.BigDecimal;

@Slf4j
public class AliPayTest {

    // 「沙箱环境」应用ID - 您的APPID，收款账号既是你的APPID对应支付宝账号。获取地址；https://open.alipay.com/develop/sandbox/app
    public static String app_id = "9021000150650717";
    // 「沙箱环境」商户私钥，你的PKCS8格式RSA2私钥
    public static String merchant_private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC+2wmj5xwJV1+NHC5x0H6q3t6hV5/sjZjpPyH+DGZuK6mKv54P6STPoiM34xRQYxzMeJR41JE9w3uSgtegCtQAox+jxobHuEQjNFep0CcOCAEslu8ECEPvpluHoQlkgxSU3zVyewFtZ9oePkCOR2UYWBVo7te9Stp9Rj0xOIk7SzFZNEVVYz0XEYAQlGN7U30rnem105PtK/23WuG2BlZhxn9rHSDpCEa4Hf7Hx04dQXHr+jZb7l6ir84bJdioNn+v+zcZg75M0iJ5mqJGD4O/xDJadEiALoWThIEkCvskgJRpdJPLxeeFHXxjGWL0yD0QqD3qBH/dEG0wVOJlw0w5AgMBAAECggEAMBJFlFXyttueApHVlO856FnoY2UJr/BeUmmHa1C+QAOZWYw4CLPlhLLHAh2dET5Vk57PbrvDtXXWWym/m9z+Vwa/QmYPrqBX8TIO3oPCQoN7oDqIC1D1o5gYN8o07m8hsPmjoakfy+m7g6CUbAHJkd8lzV9TUadX7vPRF+OwlRFEurfmhRoDKeQCfhlWNzS05wxv1D9YkRpYrromngp2RUGHR3xWQoj3qAGEB0PcCkVDSjQc2kjpMQJYXEyV5NhxeHtu2QDYPxwLwAFsHUQPrI1w91wY1FwQg2/dFE7QeZafvErTXlNtLjosIX9HIt6M67TvCgw9bH9fP3ahF27MvQKBgQDuY06M04FrNHyqh9qiwxfcC8g1myOzMAkPor8+PpR7INPfV8SusYBzDI5jhSOPWItcbIua9fthFKwvR/RycSLzn7sQ1RKqFnQtsZ0y07KVkDqvdi6pS1CY4qFRZpyPrFxtYB9K5gGcvYP7dRVU+jimpPEsj6+WkYW8gf6vNWhiJwKBgQDM9L1s/v88Snh6f0CkONTKVZz9lrjMVoxwKk6aJJjDPDx7/KWa8cT9W4ywukJM0y0Sky8JWQy6L86HYavKOSY27C3cGT1WptyV+fyodgkrZ22iZIbhCIePLpgWAjKvJHiPhN2gOVSDk9OX20Zv3dgICFajsSjr83y8hD+UcTK6nwKBgQCl91eJrfsNYyZkJ18tL/xdg4po39C0AP5d92WD9Ve0fX9koBtbsFKIRrafTOMb+n5T43IyeY0A4r6Z0FO8lU3LJWq8ZkuvRSCva1fROhe8DwT8gaAs1zWOq0G6hWD8mfhjYaeHoqh+sma/25z1Y5urUWxjJMoPXtMoEaz52IoKwwKBgFwFkrtKbmyyfw947RwOzDOgZuFQ993/CgUeabY5skEOXZXJpM1BuhGLNkrvBe+abUVGwjqvOdCqwE72onwkVq0YM6r7xheOycGowTEd9hX/1TCxdAG7o6m84NoY2IrclCjUHfHfa7u79qfa8vAtKd7JZ6UNWPM/moTF2AodHQq/AoGAYr+nA0KUXfQATwCr/8zqdGu4I4HEd+zNsHTJZHUrS4mfRdyiHK5z/YVa3oDONRy0D6hmYsmxIIzRfGZ6qfwWiKHIBStEmgtDuakiFshMn4DNGzUysUlYS3JSpiTxuN6bugupc7tA8O73Bc9V3JxxTfuMg1gI2dNSIR/pUF+I5ow=";
    // 「沙箱环境」支付宝公钥
    public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhmEzYGJQ0KxWSiVmtCM04Xb2ggRLIXt/D6DG3HLR9cjw3p3WGXDlTz5703s4cGOywL8BclYn/+G8BR4PqZcnqdRSVpkwO7nTCgZbk5GBFpJwA2toEMQJSkFhtDjuroU8QbwH3iy4PLoaBDz/Cp8Zxsn33F3H8ZtxeAa7lSVkpanS3Gf70XhOSMbdFmgz/osLhiyF0gb+NVeqWCB7eCkQeKsuoKZ/13j5qt1AOaj39mr6mJv29NGDRUQgrjsYHp5/QMpdcC9hxXjW/JNQBt3FuxbHgvkJ2SP1SZ4ZdGgbj9YZbGQs4m58SLBiaBoId9/DFckjhJ+CEShSt/J11Y+VAwIDAQAB";
    // 「沙箱环境」服务器异步通知回调地址
    public static String notify_url = "http://3196toke2098.vicp.fun/api/v1/alipay/alipay_notify_url";
    // 「沙箱环境」页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    public static String return_url = "https://gaga.plus";
    // 「沙箱环境」
    public static String gatewayUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    // 签名方式
    public static String sign_type = "RSA2";
    // 字符编码格式
    public static String charset = "utf-8";

    private AlipayClient alipayClient;

    @Before
    public void init() {
        this.alipayClient = new DefaultAlipayClient(gatewayUrl,
                app_id,
                merchant_private_key,
                "json",
                charset,
                alipay_public_key,
                sign_type);
    }

    // 拿订单信息去支付宝，支付宝返回一个用于支付的 form 表单，用html 打开，即可完成模拟支付
    @Test
    public void test_aliPay_pageExecute() throws AlipayApiException {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setNotifyUrl(notify_url);
        request.setReturnUrl(return_url);

        JSONObject bizContent = new JSONObject();
        // 我们自己生成的商品订单信息，拿唯一的商品单号去支付宝进行付款，就可以保证订单唯一，幂等性
        bizContent.put("out_trade_no", "xfg000091004001");
        bizContent.put("total_amount", "0.01"); // 订单的总金额
        bizContent.put("subject", "测试商品");   // 支付的名称
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        request.setBizContent(bizContent.toString());

        String form = alipayClient.pageExecute(request).getBody();
        log.info("测试结果：{}", form);

        /**
         * 会生成一个form表单；
         * <form name="punchout_form" method="post" action="https://openapi-sandbox.dl.alipaydev.com/gateway.do?charset=utf-8&method=alipay.trade.page.pay&sign=CAAYYDIbvUNRDvY%2B%2BF5vghx2dL9wovodww8CK0%2FferNP1KtyXdytBVLdZKssaFJV%2B8QksVuKlU3qneWhWUuI7atLDgzpussJlJhxTMYQ3GpAfOP4PEBYQFE%2FORemzA2XPjEn88HU7esdJdUxCs602kiFoZO8nMac9iqN6P8deoGWYO4UAwE0RCV65PKeJTcy8mzhOTgkz7V018N9yIL0%2BEBf5iQJaP9tGXM4ODWwFRxJ4l1Egx46FNfjLAMzysy7D14LvTwBi5uDXV4Y%2Bp4VCnkxh3Jhkp%2BDP9SXx6Ay7QaoerxHA09kwYyLQrZ%2FdMZgoQ%2BxSEOgklIZtYj%2FLbfx1A%3D%3D&return_url=https%3A%2F%2Fgaga.plus&notify_url=http%3A%2F%2Fngrok.sscai.club%2Falipay%2FaliPayNotify_url&version=1.0&app_id=9021000132689924&sign_type=RSA2&timestamp=2023-12-13+11%3A36%3A29&alipay_sdk=alipay-sdk-java-4.38.157.ALL&format=json">
         * <input type="hidden" name="biz_content" value="{&quot;out_trade_no&quot;:&quot;100001001&quot;,&quot;total_amount&quot;:&quot;1.00&quot;,&quot;subject&quot;:&quot;测试&quot;,&quot;product_code&quot;:&quot;FAST_INSTANT_TRADE_PAY&quot;}">
         * <input type="submit" value="立即支付" style="display:none" >
         * </form>
         * <script>document.forms[0].submit();</script>
         */
    }

    /**
     * 拿着订单号，在订单未完成情况下 ，主动向支付宝查询支付订单
     */
    @Test
    public void test_alipay_certificateExecute() throws AlipayApiException {

        AlipayTradeQueryModel bizModel = new AlipayTradeQueryModel();
        bizModel.setOutTradeNo("xfg000091004001");

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizModel(bizModel);

        String body = alipayClient.execute(request).getBody();
        log.info("测试结果：{}", body);
    }

    /**
     * 退款接口
     */
    @Test
    public void test_alipay_refund() throws AlipayApiException {
        AlipayTradeRefundRequest request =new AlipayTradeRefundRequest();
        // 退款的商品信息
        AlipayTradeRefundModel refundModel =new AlipayTradeRefundModel();
        refundModel.setOutTradeNo("xfg000091004001");
        refundModel.setRefundAmount("1.00");
        refundModel.setRefundReason("退款说明");
        request.setBizModel(refundModel);

        AlipayTradeRefundResponse execute = alipayClient.execute(request);
        log.info("测试结果：{}", execute.isSuccess());
    }

    public static void main(String[] args) {
        System.out.println(new BigDecimal("9.99").doubleValue());
    }

}